const mongoose = require('mongoose')
const Schema = mongoose.Schema
const bcrypt = require('bcrypt')
const Counter = mongoose.model('Counter')

const UserSchema = new Schema({
  rule: {
    type: String,
    default: 'user'
  },
  uid: Number,
  username: String,
  email: String,
  password: String,
  rs_password: String,
  createdAt: String,
  updatedAt: String
})


UserSchema.pre('save', function (next) {
  function GMTToStr(time){
    let date = new Date(time)
    let Str = date.getFullYear() + '-' +
    toZero(date.getMonth() + 1) + '-' + 
    toZero(date.getDate()) + ' ' + 
    toZero(date.getHours()) + ':' + 
    toZero(date.getMinutes()) + ':' + 
    toZero(date.getSeconds())
    return Str
  }

  function toZero(time) {
    return time < 10 ? '0' + time : time
  }

  if (this.isNew) {
    this.createdAt = this.updatedAt = GMTToStr(Date.now())
  } else {
    this.updatedAt = GMTToStr(Date.now())
  }

  next()
})

UserSchema.pre('save', function (next) {
  let user = this
  Counter.findOneAndUpdate({name: 'user'}, {$inc: { userId: 1} }, function(err, counter) {
    if (err) {
      return next(err)
    }
    console.log('counter')
    console.log(counter)
    if(counter && counter.userId){
      user.uid = counter.userId
    } else {
      let counter = new Counter({})
      counter.save().then((res) => {
        user.uid = counter.userId
      })
    }
    
    next()

  })
})

UserSchema.pre('save', function (next) {
  let user = this
  
  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return next(err)
    }
    console.log('salt')
    console.log(salt)
    console.log('password')
    console.log(user.password)
    bcrypt.hash(user.password, salt, (error, hash) => {
      if (error) {
        return next(error)
      }

      user.password = hash
      next()
    })
  })
})



UserSchema.methods = {
  comparePassword: function (_psd, psd) {
    return new Promise((resolve, reject) => {
      bcrypt.compare(_psd, psd, function (err, isMatch) {
        console.log(isMatch)
        console.log(_psd)
        console.log(psd)
        if (err) {
          reject(err)
        } else {
          resolve(isMatch)
        }
      })
    })
  }
}


mongoose.model('User', UserSchema)

























